/*
 * @Author: wangming
 * @Date: 2021-05-08 15:31:49
 * @LastEditors: wangming
 * @LastEditTime: 2022-04-21 10:00:21
 * @Description: 布局公共方法
 */
import draggable from 'vuedraggable';
import { mapActions, mapGetters } from 'vuex';
import { cloneDeep } from "lodash";
export default {
  components: { draggable },
  computed: {
    ...mapGetters(['getModelForm', 'getFormId', 'getModelTreeList']),
  },
  destroyed() {
    this.setModelForm({});
  },
  props: {
    config: {
      type: Object,
      default: () => { },
    },
    form: {
      type: Object,
      default: () => ({}),
    },
  },
  inject: {
    injectModelCode: {
      default: null,
    },
    injectChildren: {
      default: [],
    }
  },
  methods: {
    ...mapActions([
      'setModelForm',
      'setForm',
    ]),
    //布局内的点击事件
    async handleAdd({ newIndex, modelCode }, children) {
      let form = children[newIndex], formList = children
      //字表明细获取code injectModelCode
      if (!modelCode && !!this.injectModelCode) {
        modelCode = this.injectModelCode()
        formList = this.injectChildren()
      }
      //不再表单内的组件不是form模式
      if (!form.isFormLayout && form.__config.type === 'formItem') {
        form.__config.type = 'indexItem'
      }
      if (!modelCode) {
        let item = this.getFormModelCodeInTree(form.key, this.getModelTreeList)
        modelCode = item?.modelCode || ''
        formList = item?.children || []
      }
      this.$store.commit('changeFormList', formList)
      if (this.getFormId !== modelCode) {
        //表单组件逻辑
        this.setForm(modelCode);
      }
      if (form.key !== this.getModelForm.key) {
        this.setModelForm({});
        await this.$nextTick();
      }
      this.setModelForm(form);
    },
    /**
     *  在tree中 根据 组件key 定位所点击组件所在的form
     * @param {*} key 
     * @param {*} treelist 
     * @returns  返回组件所在formlayout  的   modelCode  和 children
     */
    getFormModelCodeInTree(key, treelist) {
      let queen = [], node = null;
      queen = queen.concat(treelist);
      while (queen?.length > 0) {
        let item = queen.shift();
        if (item._TYPE_ === 'org') {
          node = item.node
        } else if (item.key === key && !!node) {
          queen = []
        } else if (item.children) {
          let org = [];
          if (item.tagName === 'hlTableAdd' || item.tagName === 'hlLayoutForm') {
            org.push({ node: cloneDeep(node), _TYPE_: 'org' })
            let nodeCode = item.__config.modelCode || item.__config.code // 兼容老业务
            !!nodeCode && (node = { modelCode: nodeCode, children: item.children })
          }
          queen = [].concat(item.children, org, queen);
        }
      }
      return node
    },
    deltag(index, children) {
      let form = children[index];
      //删除选中项
      if (form.key === this.getModelForm.key) {
        this.setModelForm({});
      }
      children.splice(index, 1);
    },
  },
};
